package day4_thread_safe.exclusive;
/**
 * 加锁互斥的条件：
 *   线程都有加锁操作
 *   锁的是同一个对象
 */
public class Main {

    // 这个对象用来当锁对象
    static Object lock = new Object();

    static class MyThread1 extends Thread {
        @Override
        public void run() {
            synchronized (lock) {
                for (int i = 0; i < 1_0000; i++) {
                    System.out.println("我是张三");
                }
            }

            // 不加锁的代码并发执行
            for (int i = 0; i < 1_0000; i++) {
                System.out.println("我是王五");
            }
        }
    }

    static class MyThread2 extends Thread {
        @Override
        public void run() {
            synchronized (lock) {
                for (int i = 0; i < 1_0000; i++) {
                    System.out.println("我是李四");
                }
            }

            // 不加锁的代码并发执行
            for (int i = 0; i < 1_0000; i++) {
                System.out.println("我是赵六");
            }
        }
    }

    public static void main(String[] args) {
        Thread t1 = new MyThread1();
        t1.start();


        Thread t2 = new MyThread2();
        t2.start();
    }
}
